package cn.itcast.jx.service.impl;

import java.io.Serializable;
import java.util.List;

import cn.itcast.jx.dao.BaseDao;
import cn.itcast.jx.domain.Dept;
import cn.itcast.jx.service.IDeptService;
import cn.itcast.jx.util.Page;
import cn.itcast.jx.util.UtilFuns;

public class DeptServiceImpl implements IDeptService {
	 
	private BaseDao baseDao;

	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}

	@Override
	public Page<Dept> findPage(String hql, Page page, Class<Dept> entityClass,
			Object[] params) {
		
		return baseDao.findPage(hql, page, entityClass, params);
	}
	public List<Dept> find(String hql,Class<Dept> entityClass,Object[] params) {
		return baseDao.find(hql, entityClass, params);
	}

	@Override
	public void saveOrUpdate(Dept model) {
		if(UtilFuns.isEmpty(model.getId())) {
			baseDao.saveOrUpdate(model);
		}else {
			Dept dept = baseDao.get(Dept.class, model.getId());
			dept.setParent(model.getParent());
			dept.setDeptName(model.getDeptName());
			dept.setState(model.getState());
			baseDao.saveOrUpdate(dept);
		}
	}
	@Override
	public Dept get(Class<Dept> entityClass, Serializable id) {
		return baseDao.get(entityClass, id);
	}

	@Override
	public void delete(String[] ids) {
		
		String hql = "from Dept where parent.id=?";
		//将子部门的所属部门移除
		for (String id : ids) {
			List<Dept> list= baseDao.find(hql, Dept.class,new Serializable[] {id});
			for (Dept dept1 : list) {
				dept1.setParent(null);
				baseDao.saveOrUpdate(dept1);
			}
		}
		
		for(int i = 0;i < ids.length;i++) {
			Dept dept = baseDao.get(Dept.class, ids[i]);
			dept.setParent(null);
			dept.setState(0);
			baseDao.saveOrUpdate(dept);
		}
	}
	
	public List<Dept> removeDept(List<Dept> deptList,Dept dept) {
		String hql = "from Dept where state=1 and parent.id=?";
		
		List<Dept> list= baseDao.find(hql,Dept.class, new Serializable[] {dept.getId()});
		
		if(list != null && list.size() != 0) {
			for (Dept dept1 : list) {
				if(dept1.getParent().getId().equals(dept.getId())) {
					removeDept(deptList, dept1);
					deptList.remove(dept1);
				}
			}
		}
		deptList.remove(dept);
		return deptList;
	}
}
